package ReflectDemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//通过反射动态地创建对象
public class Test11 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获得Class对象
        Class c1 = Class.forName("ReflectDemo.User");

        //构造一个对象
        User user = (User)c1.newInstance();
        System.out.println(user);

        //通过构造器创建对象
        System.out.println("========");
        Constructor constructor = c1.getDeclaredConstructor(int.class, String.class);
        System.out.println(constructor.newInstance(3, "Lily"));

        //通过反射调用普通方法
        System.out.println("========");
        User user2 = (User)c1.newInstance();
        //通过反射获取一个方法
        Method setName = c1.getDeclaredMethod("setName", String.class);
        setName.invoke(user2,"May");
        System.out.println(user2.getName());

        //通过反射操作属性
        System.out.println("========");
        User user3 = (User) c1.newInstance();
        Field name = c1.getDeclaredField("name");
        name.setAccessible(true);  //不能直接操作私有属性，我们需要关闭程序的安全监测  属性或者方法的setAccessible(true)
        name.set(user3,"Jack");
        System.out.println(user3.getName());

    }
}
